<template>
<div :class="`tw-libpassword x${_uid}`">
<template v-if="!usePhone">
  <el-form ref="form"
    :label-width="labelWidth"
    class="demo-ruleForm"
    :style="{width: formWidth}"
    :model="formData">
    <template v-if="type==='find'">
    <el-form-item :label="usernameLabel"
      prop="tel"
      :rules="[{required: true, trigger: 'blur',validator:validateTel}]">
      <el-input v-model="formData.tel" @blur="checkUserRepeat"
        label-position="left" :placeholder="usernamePlaceholder"></el-input>
      <tw-countdown ref="countdown"
        :duration="59" style="margin-left:10px;position: absolute; top: 0; right: -110px;"
        sid="resetPassword">
        <a class="ml-step xvalidate xsmall tw-countdown-stopbox">
          <a class="tw-btn xweaking"
            @click="getCaptcha()">发送验证码</a>
        </a>
        <a class="tw-btn xweaking xdisabled tw-countdown-runningbox">
          <span class="js-countdown"></span>
          <span>后重发</span>
        </a>
      </tw-countdown>
    </el-form-item>

    <el-form-item :label="captchaLabel"
      prop="validateCode"
      :rules="[{required: true, trigger: 'blur', message:'验证码不能为空'}]">
      <el-input v-model="formData.validateCode" placeholder="请输入验证码"></el-input>
      <!-- <tw-countdown ref="countdown2"
        :duration="59" style="margin-left:10px"
        sid="resetPassword">
        <a class="ml-step xvalidate xsmall tw-countdown-stopbox">
          <a class="tw-btn xmain xweaking"
            @click="getCaptcha()">发送验证码</a>
        </a>
        <a class="tw-btn xmain xweaking xdisabled tw-countdown-runningbox">
          <span class="js-countdown"></span>
          <span>后重发</span>
        </a>
      </tw-countdown> -->
    </el-form-item>
    </template>
    <template v-else-if="type==='modify'">
      <el-form-item :label="oldpwdLabel"
        prop="oldpwd"
        :rules="[{required: true, trigger: 'blur',message:'旧密码不能为空'}]">
        <el-input type="password"
          v-model="formData.oldpwd"
          autocomplete="off"
          placeholder="请输入旧密码"></el-input>
      </el-form-item>
    </template>

    <el-form-item :label="newpwdLabel"
      prop="staticpwd"
      :rules="[{required: true, trigger: 'blur',validator:validatePassword, type:'2'}]">
      <el-input type="password"
        v-model="formData.staticpwd"
        autocomplete="off"
        :placeholder="passwordPlaceholder"></el-input>
    </el-form-item>
    <el-form-item :label="rptpwdLabel"
      prop="staticpwd2"
      :rules="[{required: true, trigger: 'blur',validator:validatePassword2, type:'2'}]">
      <el-input type="password"
        v-model="formData.staticpwd2"
        autocomplete="off"
        placeholder="请再次输入新密码"></el-input>
    </el-form-item>

    <el-form-item label="选择机构" v-show="chooseOrg"
      prop="curUserId">
     <el-select
        class="tw-libpassword-selectbox"
        v-model="formData.curUserId"
        @change="changeOrg"
        filterable
        :placeholder="'请选择机构'">
        <el-option v-for="org in orgList"
          :key="org.userId"
          :label="org.orgUserName"
          :value="org.userId">
        </el-option>
      </el-select>
    </el-form-item>

    <el-form-item>
      <a class="tw-btn xmain"
        @click="submitForm()">提 交</a>
    </el-form-item>
  </el-form>
</template>

  <!-- 移动端找回密码 -->
  <template v-else>
  <van-cell-group>
    <template v-if="type==='find'">
    <van-field v-model="formData.tel"
      left-icon=" tw-ico xtel" @blur="checkUserRepeat"
      :placeholder="usernamePlaceholder" />

    <van-field v-model="formData.validateCode"
      left-icon=" tw-ico xcheck"
      placeholder="请输入6位短信验证码">
      <template #button>
        <tw-countdown ref="countdown"
          :duration="59"
          sid="resetPassword">
          <a class="ml-step xvalidate xsmall tw-countdown-stopbox"
            @click="getCaptcha()">
            <span class="js-countdown"></span>发送验证码
          </a>
          <a class="ml-step xvalidate xsmall xdisabled tw-countdown-runningbox">
            <span class="js-countdown"></span>
            <span>后重发</span>
          </a>
        </tw-countdown>
      </template>
    </van-field>
    </template>
    <template v-else-if="type==='modify'">
    <van-field v-model="formData.oldpwd"
      left-icon=" tw-ico xpassword"
      type="password"
      :placeholder="passwordPlaceholder" />
    </template>

    <van-field v-model="formData.staticpwd"
      left-icon=" tw-ico xpassword"
      type="password"
      :placeholder="passwordPlaceholder" />

    <van-field v-model="formData.staticpwd2"
      left-icon=" tw-ico xpassword"
      type="password"
      placeholder="请再次输入密码" />

    <van-field v-show="chooseOrg"
      readonly
      clickable
      name="picker"
      :value="formData.orgUserName"
      placeholder="点击选择机构"
      @click="showPicker = true"
    />
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        value-key="orgUserName"
        :columns="orgList"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>

    <van-button class="tw-btn mt-medium xmain xxfull"
      type="info"
      @click="submitForm()">
      <span>提交</span>
    </van-button>

  </van-cell-group>
  </template>
</div>
</template>

<script>
import props from './props'
import style from '../tw-lib-base/style'
import TwCountdown from './countdown'

export default {
  name: 'tw-libpassword',

  props,

  components: { TwCountdown },

  mixins: [style],

  data() {
    return {
      formData: {
        tel: '',
        oldpwd: '',
        staticpwd: '',
        staticpwd2: '',
        validateCode: '',
        curUserId: '',
        orgId: '',
        orgUserName: ''
      },
      chooseOrg: false,
      showPicker: false,
      userId: null,
      orgList: [],
      pattern: {
        phone: /^1[3456789]\d{9}$/,
        email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
        password: /^[\d\w]{6,18}$/,

        letter: /[a-z]+/,
        letterUpper: /[A-Z]+/,
        digit: /\d+/,
        symbol: /([^\w\s]+|_+)/
      }
    }
  },

  computed: {
    style () {
      return {
        color: this.color,
        lineHeight: this.lineHeight,
        bgColor: this.bgColor,
        borderColor: this.borderColor,
        fontSize: this.fontSize,
        labelColor: this.labelColor,
        errColor: this.errColor,
        focusBorderColor: this.focusBorderColor,
        bcolor: this.bcolor,
        bbgColor: this.bbgColor,
        bborderColor: this.bborderColor,
        bhbgColor: this.bhbgColor,
        bcolor1: this.bcolor1,
        bhbgColor1: this.bhbgColor1
      }
    }
  },

  methods: {
    changeOrg () {
      let vm = this
      this.orgList.forEach(ele => {
        if (ele.userId = vm.formData.curUserId) {
          vm.formData.orgId = ele.orgId
        }
      });
    },
    onConfirm(value) {
      this.formData.curUserId = value.userId;
      this.formData.orgUserName = value.orgUserName;
      this.formData.orgId = value.orgId;
      this.showPicker = false;
    },
    setStyle () {
      let style = `
        .tw-libpassword.x${this._uid} .el-input__inner {
          color: ${this.color};
          height: ${this.lineHeight};
          line-height: ${this.lineHeight};
          background-color: ${this.bgColor};
          border-color: ${this.borderColor};
          font-size: ${this.fontSize};
        }
        .tw-libpassword.x${this._uid} .el-form-item__content, .tw-libpassword.x${this._uid} .el-form-item__label {
          line-height: ${this.lineHeight};
          color: ${this.labelColor};
          font-size: ${this.fontSize};
        }
        .tw-libpassword.x${this._uid} .el-form-item__error {
          color: ${this.errColor};
        }
        .tw-libpassword.x${this._uid} .el-form-item {
          margin-bottom: 20px;
        }
        .tw-libpassword.x${this._uid}.is-active .el-input__inner, .x${this._uid} .el-input__inner:focus {
          border-color: ${this.focusBorderColor};
        }

        .tw-libpassword.x${this._uid} .tw-btn.xmain {
          color: ${this.bcolor};
          background: ${this.bbgColor};
          border-color: ${this.bborderColor};
        }
        .tw-libpassword.x${this._uid} .tw-btn.xmain:hover {
          background: ${this.bhbgColor};
          border-color: ${this.bhborderColor};
        }

        .tw-libpassword.x${this._uid} .tw-btn.xweaking {
          color: ${this.bcolor1};
          background: ${this.bbgColor1};
          border-color: ${this.bborderColor};
        }
        .tw-libpassword.x${this._uid} .tw-btn.xweaking:hover {
          background: ${this.bhbgColor1};
          border-color: ${this.bhborderColor};
        }
      `

      this.addStyle(style)
    },
    validateTel (rule, value, callback) {
      if (!this.pattern.phone.test(value)) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    },

    check (pwd) {
      var result
      var checks = {}
      if (this.digitAndLetter(pwd)) {
        result = 'f'
      } else {
        checks['number'] = true
        checks['letter'] = true
        checks['letterUpper'] = true
        // 包含特殊字符
        if (this.checkSymbol(pwd)) {
          checks['symbol'] = true
        }
        result = checks
      }
      return result
    },
    checkDigital (pwd) {
      return this.pattern.digit.test(pwd)
    },
    checkLetter (pwd) {
      return this.pattern.letter.test(pwd)
    },
    checkSymbol (pwd) {
      return this.pattern.symbol.test(pwd)
    },
    checkLetterUpper (pwd) {
      return this.pattern.letterUpper.test(pwd)
    },
    digitAndLetter (pwd) {
      return this.checkDigital(pwd) && this.checkLetter(pwd) && this.checkLetterUpper(pwd) ? !1 : !0
    },

    /**
    * 功能: 验证密码
    * type : 1-注册 2-找回密码 3-登录
    */
    validatePassword (rule, value, callback) {
      if (value === '') {
        callback(new Error('新密码不能为空'))
      } else {
        if (value.length < 6 || value.length > 20) {
          callback(new Error('新密码长度为6到20位任意字符'))
          return
        }
        if (value.indexOf(' ') >= 0) {
          callback(new Error('密码不能包含空格'))
          return
        }
        var checkResult = this.check(value)
        if (!(
            checkResult !== 'f' &&
            checkResult.letter &&
            checkResult.letterUpper &&
            checkResult.number &&
            checkResult.symbol
          )) {
          callback(new Error('新密码必须包含大小写、数字、特殊字符'))
          return
        }
        // if (!this.pattern.password.test(value)) {
        //   callback(new Error('请输入密码，字母或数字，6-18位'))
        // }
        callback()
        if (this.formData.staticpwd !== '') {
          this.$refs.form.validateField('staticpwd2')
        }

      }
    },

    /**
    * 功能: 验证确认密码
    *  type : 1-注册 2-找回密码 3-登录
    */
    validatePassword2 (rule, value, callback) {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else {
        if (this.formData.staticpwd !== value) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }
    },

    /**
    * 功能: 提交表单
    * @param {String} type : 1-注册 2-找回密码
    *
    */
    submitForm () {
      const vm = this
      var userId = vm.$twApp.user.userId

      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (vm.type === 'find' && (vm.formData.curUserId === null || vm.formData.curUserId === '')) {
            window.$ui.msg('请先发送验证码!')
            return
          }

          var req = {}
          var key = window.CryptoJS.enc.Utf8.parse(window.$twApp.appKey)
          var staticPassword = window.CryptoJS.AES.encrypt(vm.formData.staticpwd, key, {
            mode: window.CryptoJS.mode.ECB,
            padding: window.CryptoJS.pad.Pkcs7
          }).toString()

          req.userId = vm.formData.curUserId
          req.staticPassword = staticPassword
          if (vm.type === 'find') {
            req.loginName = vm.formData.curUserId
            req.validateCode = vm.formData.validateCode
            req.validateTo = vm.formData.tel
            req.isAccountInfo = '0'

            if (vm.stepOneForm) {
              req.isAccountInfo = '1'
            }
          } else {
            let oldPassword = window.CryptoJS.AES.encrypt(vm.formData.oldpwd, key, {
              mode: window.CryptoJS.mode.ECB,
              padding: window.CryptoJS.pad.Pkcs7
            }).toString()
            req.oldPassword = oldPassword
          }

          if (userId) {
            req.userId = userId
          }

          if (vm.type === 'find') {
            window.axios({
              method: 'post',
              url: window.$twApp.gateway + '/openapi-uc/oauth/doUpdatePwd',
              data: req,
              headers: {
                'X-Client-Id': window.$twApp.appId
              }
            }).then((resp) => {
              if (resp.data.serverResult.resultCode === '200') {
                if (userId) {
                  window.$ui.msg('密码设置成功，请重新登录!')
                } else {
                  window.$ui.msg('密码设置成功!')
                }
                if (vm.loginSuccessUrl) {
                   window.$ui.alert('', '密码设置成功，请重新登录', {
                    confirmButtonText: '确定',
                    callback: action => {
                      window.$twApp.logoff()
                      window.location.href = vm.loginSuccessUrl
                    }
                  })
                }
              } else {
                window.$ui.msg({type: 'error', message: resp.data.serverResult.resultMessage})
              }
            }).catch((err) => {
              vm.$ui.msg('密码设置失败!')
              console.log(err)
            })
          } else {
            window.axios({
              method: 'post',
              url: window.$twApp.gateway + '/openapi-uc/uc/updatePwd',
              data: req,
              headers: {
                'X-Client-Id': window.$twApp.appId
              }
            }).then((resp) => {
              if (resp.data.serverResult.resultCode === '200') {
                if (userId) {
                  window.$ui.msg('密码设置成功，请重新登录!')
                } else {
                  window.$ui.msg('密码设置成功!')
                }
                if (vm.loginSuccessUrl) {
                  window.$ui.alert('', '密码设置成功，请重新登录', {
                    confirmButtonText: '确定',
                    callback: action => {
                      window.$twApp.logoff()
                      window.location.href = vm.loginSuccessUrl
                    }
                  })
                }
              } else {
                window.$ui.msg({type: 'error', message: resp.data.serverResult.resultMessage})
              }
            }).catch((err) => {
              vm.$ui.msg('密码设置失败!')
              console.log(err)
            })
          }
        }
      })
    },
    // 点击获取验证码
    getCaptcha () {
      if (!this.pattern.phone.test(this.formData.tel.trim())) {
        window.$ui.msg('请输入手机号码')
        return
      }

      const vm = this
      this.sendVerificationCode().then(res => {
        this.$refs.countdown.start()
      }).catch(e => {
        this.$refs.countdown.stop()
      })
    },
    checkUserRepeat () {
      let vm = this
      if (!vm.formData.tel || !this.pattern.phone.test(this.formData.tel.trim())) {
        return
      }
      vm.orgList = []
      vm.chooseOrg = false
      window.axios.post(window.$twApp.gateway + '/openapi-uc/uc/checkUserRepeat', {
        name: vm.formData.tel
      }).then((resp) => {
        if (resp.data.pageInfo && resp.data.pageInfo.list && resp.data.pageInfo.list.length > 0) {
          var userId = resp.data.pageInfo.list[0].userId
          let ui = resp.data.pageInfo.list[0]

          if (resp.data.pageInfo.list.length > 1) {
            let userList = resp.data.pageInfo.list
            for (let i = 0; i < userList.length; i++) {
              let u = userList[i]
              let orgObject = {}
              let roleName = ''
              let orgName = ''
              let realName = ''
              if (u.roleName) {
                roleName = u.roleName
              }
              if (u.orgName) {
                orgName = u.orgName
              }
              if (u.realName) {
                realName = u.realName
              }
              orgObject.orgUserName =
                orgName + '(' + realName + roleName + ')'
              orgObject.userId = u.userId
              orgObject.orgId = u.orgId
              vm.orgList.push(orgObject)
            }
            vm.chooseOrg = true
          }

          // 修改密码
          if (vm.$twApp.user.userId && userId !== vm.$twApp.user.userId) {
            window.$ui.msg('只能重置当前登录账号的密码!')
            return
          }

          // 找回密码
          vm.formData.curUserId = userId
          vm.formData.orgId = ui.orgId
          vm.formData.orgUserName = (ui.orgName || '') + '(' + (ui.realName || '') + (ui.roleName || '') + ')'
        } else {
          window.$ui.msg('该手机号未注册，请先注册!')
        }
      }).catch((err) => {
        console.log(err)
      })
    },

    /**
    * 功能: 发送验证码
    */
    async sendVerificationCode () {
      let vm = this
      // 找回密码
      let userId = vm.formData.curUserId || vm.$twApp.user.userId // = userId

      await window.axios.post(window.$twApp.gateway + '/openapi-uc/validate/v2/sendValidateCode', {
        orgId: vm.formData.orgId || vm.$twApp.user.orgId,
        type: 1,
        to: userId,
        toDo: 2
      }).then((resp) => {
        if (resp.data.serverResult.resultCode === '200') {
          window.$ui.msg('验证码发送成功!')
        } else {
          window.$ui.msg('验证码发送失败!')
        }
      }).catch((err) => {
        window.$ui.msg('验证码发送失败!')
      })
    }
  },

  mounted () {
    this.setStyle()
    if (this.type==='modify') {
      this.checkUserRepeat()
    }
  },

  watch: {
  }
}
</script>

<style lang="scss">
  @import './css/index.scss';
</style>
